package org.tong.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;
import org.tong.bean.Score;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class ScoreDao extends JdbcTemplate {

    @Autowired
    @Qualifier("businessDataSource")
    private DataSource dataSource;


    @Override
    public DataSource getDataSource() {
        return dataSource;
    }


    public int insert(Score score) {
        Assert.notNull(score, "score can not be null");
        return update("insert into t_score (score,t_id)values(?,?)", score.getScore(), score.getsId());
    }

    public List<Score> queryAllScores() {
        return query("select * from t_score", getRowMapper());
    }

    private RowMapper getRowMapper() {
        return new RowMapper() {
            @Override
            public Object mapRow(ResultSet resultSet, int i) throws SQLException {
                Score score = new Score();
                score.setId(resultSet.getInt(1));
                score.setScore(resultSet.getFloat(2));
                score.setsId(resultSet.getInt(3));
                return score;
            }
        };
    }
}
